<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\User;
use app\admin\model\UserDeliveryAddress;
use app\common\controller\Api;
use app\common\model\ActivityOrder;
use app\common\model\Transaction;
use fast\Random;
use think\Db;
use think\Log;

class Order extends Api
{
    protected $noNeedLogin = ['getShareImage', 'createTransaction', 'getOrderByOrderNo'];
    protected $noNeedRight = '*';

    // 创建订单
    public function send()
    {
        $activity_id = input('post.id/d', 0);
        $dre_id = input('post.user_id/d', 0);

        $model = new \app\common\model\Activity();
        $info = $model->getInfo($activity_id);
        if (is_string($info)) {
            $this->error($info);
        }

        $orderModel = new ActivityOrder();

        $res = [];
        Db::startTrans();
        try {
            $order_no = 'AC' . date('YmdHis') . Random::numeric(6);
            $data = [
                'activity_id'  => $activity_id,
                'shop_id'      => $info['user_id'],
                'buy_id'       => $this->auth->id,
                'dre_id'       => $dre_id,
                'order_no'     => $order_no,
                'money'        => $info['money'],
                'pay_status'   => 1,
                'status'       => 1,
            ];

            // 获取默认地址
            $address = Db::name('user_deliveryaddress')->where('user_id', $this->auth->id)->find();
            if ($address) {
                $data['take_over_name']    = $address['delivery_name'];
                $data['take_over_tel']     = $address['delivery_phone'];
                $data['take_over_address'] = $address['delivery_district'] . ' ' . $address['delivery_address'];
            }

            $data['pay_status'] = 2;
            $data['pay_time'] = time();

            $orderModel->save($data);

            $res = [
                'order_no'   => $order_no,
                'money'      => $info['money'],
                'pay_status' => $data['pay_status'],
                'pay_params' => [], // $pay_params,
            ];

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage();
            $this->error('订单创建失败');
        }

        $this->success('success', $res);
    }

    public function createTransaction()
    {
        $data = $_GET['info'];
//        Log::info('createTransaction', $data);
        $jsonString = urldecode($data);
        $params = json_decode($jsonString, true);

        $order_no = 'AC' . date('YmdHis') . Random::numeric(6);
        if ('activity' == $params['type']) {
            $activity_id = $params['id'];
            $user_id = $params['really_user_id'];

            $model = new \app\common\model\Activity();
            $info = $model->getInfo($activity_id);

            if (is_string($info)) {
                echo $info;
                exit;
            }
            $fee = $info['money'];
            $orderTitle = $info['title'] . '订单';
        } else if ('buy_merchant_role' == $params['type'] or 'renew_merchant_role' == $params['type']) {
            $user_id = $params['user_id'];
            $fee   = config('site.merchant_renewal_fee');   // 商家续费费用(金额)
            $orderTitle = "用户{$user_id}申请成为商家订单";
        }

        $transaction = new Transaction();
        $transaction->save([
            'out_trade_no' => $order_no,
            'fee' => $fee,
            'status' => 1,
            'user_id' => $user_id,
            'extra_info' => $jsonString,
        ]);

        $checkpaymentUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/pages/index/checkpayment?orderid=' . $order_no;

        if ('h5' == $params['pay_way']) {
            $payParams = [
                'amount'    => $fee,
                'orderid'   => $order_no,
                'type'      => "wechat",
                'title'     => $orderTitle,
                'notifyurl' => url('/api/notify/wx_notify', [], false, true),
                'returnurl' => $checkpaymentUrl,
                'method'    => "wap",
            ];
            $pay_url = Service::submitOrder($payParams);

            echo $pay_url;

        } else if ('jssdk' == $params['pay_way']) {
            // 得到openid
            $userModel = User::get($user_id);
            $payParams = [
                'openid' => $userModel->mp_openid,
//                'openid' => 'oi1qd6Mc0KbA1fbLO7q3zB0ApwOk',
                'amount'    => $fee,
                'orderid'   => $order_no,
                'type'      => "wechat",
                'title'     => $orderTitle,
                'notifyurl' => url('/api/notify/wx_notify', [], false, true),
                'returnurl' => $checkpaymentUrl,
                'method'    => "mp",
            ];
            $response = Service::submitOrder($payParams);
            $responseArray = $response->toArray();
            $responseArray['return_url'] = $checkpaymentUrl;

            $this->success('ok', $responseArray);
        }

    }

    public function getTransactionInfo()
    {
        $ourTradeNo = input('out_trade_no');
        $transaction = Transaction::where('out_trade_no', $ourTradeNo)->find();

        if ($transaction) {
            $this->success('ok', $transaction);
        } else {
            $this->error('无此订单');
        }
    }

    public function getUserList()
    {
        $user_id = $this->auth->id;
        $type = input('type/d', 0);
        $where = [
            'buy_id' => $user_id,
        ];

        if ($type) {
            $where['status'] = $type;
        }

        $model = new ActivityOrder();
        $list = $model
            ->with('activity')
            ->where($where)
            ->order('id desc')
            ->paginate(10);

        $this->success('success', $list);
    }

    public function sendTake()
    {
        $order_id = input('post.id/d', 0);
        $orderModel = new ActivityOrder();

        $info = $orderModel->where('id', $order_id)->find();
        if (empty($info)) {
            $this->error('订单不存在');
        }

        if ($info['pay_status'] != 2) {
            $this->error('订单未支付');
        }

        if ($info['status'] != 1) {
            $this->error('订单已发货不可修改');
        }

        $data = [
            'take_over_way' => input('post.take_over_way', 0),
            'take_over_name'    => input('post.take_over_name', ''),
            'take_over_tel'     => input('post.take_over_tel', ''),
            'take_over_district'     => input('post.take_over_district', ''),
            'take_over_address' => input('post.take_over_address', ''),
        ];

        if (in_array($data['take_over_way'], [1, 2])) {
            if (1 == $data['take_over_way']) {
                if (empty($data['take_over_name'])) {
                    $this->error('收货人姓名不能为空');
                }

                if (empty($data['take_over_tel'])) {
                    $this->error('收货人电话不能为空');
                }

                if (empty(($data['take_over_district']))) {
                    $this->error('收货人所在地区不能为空');
                }

                if (empty($data['take_over_address'])) {
                    $this->error('收货人地址不能为空');
                }
            } else if (2 == $data['take_over_way']) {
                if (empty($data['take_over_name'])) {
                    $this->error('收货人姓名不能为空');
                }

                if (empty($data['take_over_tel'])) {
                    $this->error('收货人电话不能为空');
                }
            }
        } else {
            $this->error('取货方式必须选择');
        }

        $res = $orderModel->allowField(true)->save($data, ['id' => $order_id]);

        //要把用户这一次提交的地址数据，保存在全局的用户地址管理表里, 如果没有就创建

        $userAddress = UserDeliveryAddress::where('user_id', $this->auth->id)->find();
        if ($userAddress) {
            if (!empty($data['take_over_name'])) {
                $userAddress->delivery_name = $data['take_over_name'];
            }
            if (!empty($data['take_over_tel'])) {
                $userAddress->delivery_phone = $data['take_over_tel'];
            }
            if (!empty($data['take_over_district'])) {
                $userAddress->delivery_district = $data['take_over_district'];
            }
            if (!empty($data['take_over_address'])) {
                $userAddress->delivery_address = $data['take_over_address'];
            }

            $userAddress->save();
        } else {
            UserDeliveryAddress::create([
               'user_id' => $this->auth->id,
                'delivery_name' => $data['take_over_name'] ?? '',
                'delivery_phone' => $data['take_over_tel'] ?? '',
                'delivery_district' => $data['take_over_district'] ?? '',
                'delivery_address' => $data['take_over_address'] ?? '',
            ]);
        }

        if ($res) {
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }

    public function getShopList()
    {
        $user_id = $this->auth->id;
        $type = input('type/d', 0);
        $activity_id = input('activity_id/d', 0);
        $where = [
            'shop_id' => $user_id,
        ];

        if ($type) {
            $where['status'] = $type;
        }

        if ($activity_id) {
            $where['activity_id'] = $activity_id;
        }

        $model = new ActivityOrder();
        $list = $model
            ->with(['activity', 'user', 'dre'])
            ->order('id', 'desc')
            ->where($where)
            ->paginate(10);

        $this->success('success', $list);
    }

    public function getShopInfo()
    {
        $id = input('id/d', 0);
        $user_id = $this->auth->id;

        $model = new ActivityOrder();
        $where = [
            'shop_id' => $user_id,
            'id'      => $id,
        ];

        $info = $model->where($where)->find();

        if (empty($info)) {
            $this->error('订单不存在');
        }

        $this->success('success', $info);
    }

    public function getUserInfo()
    {
        $id = input('id/d', 0);
        $user_id = $this->auth->id;

        $model = new ActivityOrder();
        $where = [
            'buy_id' => $user_id,
            'id'     => $id,
        ];

        $info = $model->where($where)->find();

        if (empty($info)) {
            $this->error('订单不存在');
        }

        $this->success('success', $info);
    }

    // 发货
    public function sendOut()
    {
        $id = input('id/d', 0);
        $user_id = $this->auth->id;

        $model = new ActivityOrder();
        $where = [
            'shop_id' => $user_id,
            'id'      => $id,
        ];

        $info = $model->where($where)->find();

        if (empty($info)) {
            $this->error('订单不存在');
        }

        if ($info['status'] == 3) {
            $this->error('订单已发货不可修改');
        }

        if (0 == $info->take_over_way) {
            $this->error('用户还未提供取货方式');
        }

        if (1 == $info->take_over_way) {
            $data = [
                'send_out_info'   => input('send_out_info', ''),
                'logistics_info'  => input('logistics_info', ''),
                'send_out_images' => input('send_out_images', ''),
                'note' => input('note', ''),
                'status'          => 2,
            ];

            if (empty($data['send_out_info'])) {
                $this->error('发货信息不能为空');
            }
        }

        if (2 == $info->take_over_way) {
            $data = [
                'note' => input('note', ''),
                'status'          => 2,
            ];
        }

//        if (empty($data['logistics_info'])) {
//            $this->error('物流信息不能为空');
//        }

//        if (empty($data['send_out_images'])) {
//            $this->error('请上传照片');
//        }

        $res = $model->allowField(true)->save($data, ['id' => $id]);

        if ($res) {
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }

    // 确认收货
    public function sendOutIn()
    {
        $id = input('id/d', 0);
        $user_id = $this->auth->id;

        $model = new ActivityOrder();
        $where = [
            'buy_id' => $user_id,
            'id'     => $id,
        ];

        $info = $model->where($where)->find();

        if (empty($info)) {
            $this->error('订单不存在');
        }

        $data = [
            'status'         => 3,
        ];

        $res = $model->allowField(true)->save($data, ['id' => $id]);

        // 更新活动人的总提现金额
        $user = User::get($info->shop_id);
        $model_order = new \app\admin\model\activity\Order();
        $order = $model_order->field('sum(money) as order_amount')
            ->where('shop_id', $info->shop_id)
            ->where('status', 3)
            ->find();

        if ($order['order_amount']) {
            $user->all_withdraw_money = $order['order_amount'];
            $user->save();
        }

        if ($res) {
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }

    //下载分享图片
    public function getShareImage()
    {
        $fileName = $this->request->get('filename');
        $fileName = explode('?',$fileName)[0];
        $publicPath =  ROOT_PATH . 'public/';
        $imagePath = $publicPath . 'uploads/qrcode/' . $fileName;

        // 设置响应头信息
        header("Content-Type: image/png");
        header("Content-Disposition: attachment; filename=\"share_image.png\"");
        header("Content-Length: " . filesize($imagePath));

        readfile($imagePath);

        exit;
    }

    public function zeroOrderPay()
    {
        $activityId = $this->request->get('activity_id');
        $activity = \app\admin\model\Activity::where('id', $activityId)->find();

        if (!$activity) {
            $this->error('此活动id不存在');
        }

        $buyId = $this->request->post('really_user_id');
        $buyer = User::get($buyId);
        if (!$buyer) {
            $this->error('此购买用户id不存在');
        }
        $dreId = $this->request->post('user_id'); //是前端给的推荐人的ID
        $dreer = User::get($dreId);
        if (!$dreer) {
            $this->error('此推荐人的用户id不存在');
        }



        $data = [
            'activity_id'  => $activityId,
            'shop_id'      => $activity->user_id,
            'buy_id'       => $buyId, //购买人的id,
            'dre_id'       => $dreId,
            'order_no'     => 'AC' . date('YmdHis') . Random::numeric(6),
            'money'        => 0,
            'pay_status'   => 2,
            'status'       => 1,
            'pay_time'     => time()
        ];

        // 获取默认地址
        $address = Db::name('user_deliveryaddress')->where('user_id', $this->auth->id)->find();
        if ($address) {
            $data['take_over_name']    = $address['delivery_name'];
            $data['take_over_tel']     = $address['delivery_phone'];
            $data['take_over_district'] = $address['delivery_district'];
            $data['take_over_address'] = $address['delivery_address'];
        }

        $orderModel = new ActivityOrder();
        $orderModel->save($data);

        $this->success('购买成功', ['order_id' => $orderModel->id]);
    }

    public function getOrderByOrderNo()
    {
        $orderNo = $this->request->get('order_no');
        $order = ActivityOrder::get([
            'order_no' => $orderNo
        ]);

        if (!$order) {
            $this->error('无此订单');
        }

        $this->success('查询成功', $order);
    }


}

